package de.ifi.lmu.snitzelhunt.contacts;

import java.util.ArrayList;
import java.util.Iterator;

import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import de.ifi.lmu.snitzelhunt.R;
import de.ifi.lmu.snitzelhunt.basics.Route;
import de.ifi.lmu.snitzelhunt.basics.User;
import de.ifi.lmu.snitzelhunt.creator.Globals;
import de.ifi.lmu.snitzelhunt.util.DatabaseUtility;
import de.ifi.lmu.snitzelhunt.util.responses.AsyncDatabase_Route_ReadResponse;

public class Activity_GetContacts extends FragmentActivity implements
		AsyncDatabase_Route_ReadResponse {
	// Variables to store Contacts in

	public ArrayList<User> users = new ArrayList<User>();
	private String ownCellNumber;

	private SharedPreferences settings;
	private ArrayList<User> lastSelected;
	private int nrOfLastSelected = 0;
	private Route tempRoute;
	private DatabaseUtility dbUtil;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_getcontacts);

		settings = getSharedPreferences(Globals.PREF_NAME, 0);
		dbUtil = new DatabaseUtility();

		readContacts();

	}

	public void readContacts() {
		String Name = "";
		String Phone = "";

		ContentResolver cr = getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
				null, null, null);

		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				String id = cur.getString(cur
						.getColumnIndex(ContactsContract.Contacts._ID));
				Name = cur
						.getString(cur
								.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				if (Integer
						.parseInt(cur.getString(cur
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
					// get the phone number
					Cursor pCur = cr.query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID
									+ " = ?", new String[] { id }, null);
					while (pCur.moveToNext()) {
						Phone = pCur
								.getString(pCur
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					}
					pCur.close();

					if (!Phone.equals("")) {
						if (Phone.startsWith("01")) {
							Phone = Phone.replaceFirst("0", "+49");

						}
						if (Phone.startsWith("+49")) { 
							User temp = new User(Name, Phone);
							users.add(temp);
						}
					}
				}
			}
			if (settings.getBoolean(Globals.GET_LAST_FLAG, false)) {
				Log.i("getcontacts", "last flag is on");

				dbUtil.readRoute(settings.getLong(Globals.LAST_LOCAL_ID, 0),getBaseContext(), this);

			} else {
				Log.i("getcontacts", "last flag is off");
				firePopup();
			}
		}
	}

	public String getOwnCellNumber() {
		TelephonyManager tMgr = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);
		String mPhoneNumber = tMgr.getLine1Number();

		if (mPhoneNumber != null) {
			System.out.println("And my own PhoneNr: " + mPhoneNumber);
		} else {
			mPhoneNumber = "Eigene Nummer konnte nicht gelesen werden. SIM Karte im Handy?";
		}
		return mPhoneNumber;

	}

	public void firePopup() {
		Log.i("getContacts", "fire");
		
		Popup_Contacts contacts = new Popup_Contacts();
		ownCellNumber = getOwnCellNumber();

		contacts.setOwnCellNumber(ownCellNumber);
		contacts.setUserArray(users, nrOfLastSelected);
		contacts.setCancelable(false);
		
		contacts.show(getSupportFragmentManager(), ALARM_SERVICE);

	}

	@Override
	public void onBackPressed() {
		//do nothing
		
	}
	
	@Override
	public void processDatabase_Route_Read(Route route) {

		Log.i("getContacts", route.toString());
		
		if (route.getUsers().size() != 0) {
			Log.i("getcontacts", "found saved contacts: " + route.getUsers().size());

			nrOfLastSelected = route.getUsers().size();

			for (User u : route.getUsers()) {
				for (Iterator<User> it = users.iterator(); it.hasNext();) {
					User v = it.next();
					if (v.getCellNumber().equals(u.getCellNumber())) {
						Log.i("contacts", "removed user "+v.getName());
						it.remove();
					}
				}
			}
				

			ArrayList<User> tempUserList = new ArrayList<User>();
			tempUserList.addAll(route.getUsers());
			tempUserList.addAll(users);
			users = tempUserList;
			firePopup();
		}

	}
}